package common.library.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;

import common.library.models.Size;
import lombok.var;

public class CameraUtil {

    public static Size getSize(Camera camera) {
        var size = camera.getParameters().getPictureSize();
        return new Size(size.width, size.height);
    }

    public static CameraManager getManager(Activity activity) {
        return (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    }

    public static String[] getIds(CameraManager cameraManager) {
        try {
            return cameraManager.getCameraIdList();
        } catch (Exception ex) {
            LogUtil.error(ex.getMessage());
            return null;
        }
    }

    public static String[] getIds(Activity activity) {
        return getIds(getManager(activity));
    }

    public static void printIds(Activity activity) {
        var cameraManager = getManager(activity);
        var ids = getIds(cameraManager);
        for (String id : ids)
            LogUtil.info("CameraId: " + id);
    }

    public static Size[] getOutputSizes(Camera camera) {
        var cameraSizes = camera.getParameters().getSupportedPictureSizes();
        var sizes = SizeUtil.convert(cameraSizes);
        return sizes;
    }

    public static Size[] getOutputSizes(CameraManager cameraManager, String cameraId) throws Exception {
        var cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);//相机属性
        StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        var outputSizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
        var sizes = SizeUtil.convert(outputSizes);
        return sizes;
    }

    public static Size getMaxOutputSize(Camera camera) {
        var sizes = getOutputSizes(camera);
        return SizeUtil.getMax(sizes);
    }

    public static Size getMaxOutputSize(CameraManager cameraManager, String cameraId) throws Exception {
        var sizes = getOutputSizes(cameraManager, cameraId);
        return SizeUtil.getMax(sizes);
    }

    public static Size getScreenOutputSize(Activity activity, Camera camera) {
        var sizes = getOutputSizes(camera);
        return SizeUtil.getMatch(sizes, ApplicationUtil.getScreenSize(activity));
    }

    public static Size getScreenOutputSize(Activity activity, CameraManager cameraManager, String cameraId) throws Exception {
        var sizes = getOutputSizes(cameraManager, cameraId);
        return SizeUtil.getMatch(sizes, ApplicationUtil.getScreenSize(activity));
    }
}
